package org.steven.crm.core.auth;

import org.steven.crm.core.auth.dto.GrantTokenRequest;
import org.steven.crm.core.exception.ServiceException;
import org.steven.crm.core.service.accesstoken.AccessTokenService;
import org.steven.crm.core.service.system.SystemConfigService;
import org.steven.crm.core.service.user.UserService;
import org.steven.crm.core.service.user.WechatUserService;
import org.steven.crm.core.service.weixin.WeixinUserService;
import org.apache.commons.lang3.StringUtils;
import weixin.popular.bean.sns.SnsToken;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author wuzw
 * @Date 2024/1/10 17:31
 * @Version 1.0
 */
public class WechatUserAuthHandler extends AuthHandler {
    private static UserService userService = new UserService();

    private static WechatUserService wechatUserService = new WechatUserService();

    private static AccessTokenService accessTokenService = new AccessTokenService();

    private static WeixinUserService weixinUserService = new WeixinUserService();

    private static SystemConfigService systemConfigService = new SystemConfigService();


    @Override
    public Map<String, String> createToken(Map<String, String> client, GrantTokenRequest grantTokenRequest) throws Exception {
        String wxAppId = systemConfigService.getValue("wxAppId");
        String wxAppSecret = systemConfigService.getValue("wxAppSecret");
        String openId = weixinUserService.getOpenId(grantTokenRequest.getCode(), wxAppId, wxAppSecret);
        if (StringUtils.isEmpty(openId)) {
            throw new ServiceException("获取微信用户openId失败");
        }
        Map<String, String> wechatUser = wechatUserService.readUserIdByOpenId(openId);
        if (wechatUser.isEmpty()) {
            Map<String, String> data = new HashMap<>();
            data.put("openId", openId);
            data.put("bindCode", UUID.randomUUID().toString());
            wechatUser = wechatUserService.create(data);
            wechatUser.put("bindUserFlag", "0");

            return wechatUser;
        } else if (StringUtils.isEmpty(wechatUser.get("userId"))) {
            Map<String, String> data = new HashMap<>();
            data.put("bindCode", UUID.randomUUID().toString());
            wechatUser = wechatUserService.update(wechatUser.get("id"), data);
            wechatUser.put("bindUserFlag", "0");

            return wechatUser;
        }

        return accessTokenService.create(client.get("id"), wechatUser.get("userId"));
    }

    @Override
    protected Map<String, String> authorize(Map<String, String> accessToken)  throws Exception {
        Map<String, String> user = userService.read(accessToken.get("userId"));

        return user;
    }
}
